package com.starsea.book.ui.newpage.weidget.flow

import android.view.View
import android.view.ViewGroup

/**
 * @author Lee
 * @createTime 2023-10-31 16 GMT+8
 * @desc :
 */
abstract class FlowAdapter<FlowContentEntity> {
  private var onDataChangedListener: OnDataChangedListener? = null
  private var data: MutableList<FlowContentEntity>? = null

  /**
   * 子View创建
   *
   * @param parent
   * @param item
   * @param position
   * @return
   */
  abstract fun getView(parent: ViewGroup?, item: FlowContentEntity, position: Int): View?

  /**
   * 初始化View
   *
   * @param view
   * @param item
   * @param position
   * @return
   */
  abstract fun initView(view: View?, item: FlowContentEntity, position: Int)

  /**
   * 折叠View 默认不设置
   *
   * @return
   */
  fun foldView(): View? {
    return null
  }

  val count: Int
    /**
     * 数据的数量
     *
     * @return
     */
    get() = if (data == null) 0 else data!!.size

  /**
   * 获取数据
   *
   * @return
   */
  fun getData(): MutableList<FlowContentEntity>? {
    return data
  }

  /**
   * 设置新数据
   *
   * @param data
   */
  fun setNewData(data: MutableList<FlowContentEntity>) {
    this.data = data
    notifyDataChanged()
  }

  /**
   * 添加数据
   *
   * @param data
   */
  fun addData(data: List<FlowContentEntity>?) {
    if (this.data == null) {
      this.data = ArrayList()
    }
    this.data!!.addAll(data!!)
    notifyDataChanged()
  }

  /**
   * 添加数据
   *
   * @param index
   * @param data
   */
  fun addData(index: Int, data: List<FlowContentEntity>?) {
    if (this.data == null) {
      this.data = ArrayList()
    }
    this.data!!.addAll(index, data!!)
    notifyDataChanged()
  }

  /**
   * 添加数据
   *
   * @param data
   */
  fun addData(data: FlowContentEntity) {
    if (this.data == null) {
      this.data = ArrayList()
    }
    this.data!!.add(data)
    notifyDataChanged()
  }

  fun addData(index: Int, data: FlowContentEntity) {
    if (this.data == null) {
      this.data = ArrayList()
    }
    this.data!!.add(index, data)
    notifyDataChanged()
  }

  fun removeAt(index: Int) {
    if (this.data != null) {
      this.data!!.removeAt(index)
      notifyDataChanged()
    }
  }

  fun clearAll() {
    if (this.data != null) {
      this.data!!.clear()
      notifyDataChanged()
    }
  }

  /**
   * 获取指定位置的数据
   *
   * @param position
   * @return
   */
  fun getItem(position: Int): FlowContentEntity? {
    return if (data != null && position >= 0 && position < data!!.size) {
      data!![position]
    } else null
  }

  /**
   * 刷新数据
   */
  fun notifyDataChanged() {
    if (onDataChangedListener != null) {
      onDataChangedListener!!.onChanged()
    }
  }

  fun setOnDataChangedListener(listener: OnDataChangedListener?) {
    onDataChangedListener = listener
  }

  interface OnDataChangedListener {
    fun onChanged()
  }
}
